package org.example.service.impl;

import org.example.dao.ICartDao;
import org.example.entity.CartEntity;
import org.example.entity.CartVoEntity;
import org.example.entity.ProductEntity;
import org.example.entity.UserEntity;
import org.example.service.ICartService;
import org.example.service.IProductService;
import org.example.util.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Coder
 */
@Service
public class CartServiceImpl implements ICartService {
    private final IProductService productService;
    private final ICartDao cartDao;

    public CartServiceImpl(IProductService productService, ICartDao cartDao) {
        this.productService = productService;
        this.cartDao = cartDao;
    }

    @Override
    public void save(CartEntity cartEntity, UserEntity userEntity) {
        //判断购物车中是否有该商品
        CartEntity newCartEntity = null;
        List<CartEntity> cartEntityList = cartDao.selectSelective(cartEntity);
        if (!cartEntityList.isEmpty()) {
            newCartEntity = cartEntityList.get(0);
        }
        if (newCartEntity == null) {
            ResponseEntity<ProductEntity> productResponseEntity = productService.getById(cartEntity.getPid());
            ProductEntity productEntity = productResponseEntity.getData();
            Long price = Long.valueOf(productEntity.getPrice());
            cartEntity.setPrice(price);
            cartDao.insertSelective(cartEntity);
        } else {
            //修改商品数量
            newCartEntity.setNum(newCartEntity.getNum() + cartEntity.getNum());
            cartDao.updateSelective(newCartEntity);
        }
    }

    @Override
    public List<CartVoEntity> listCart(Integer uid) {
        CartEntity cartEntity = new CartEntity();
        cartEntity.setUid(uid);
        return cartDao.selectCartVoSelective(cartEntity);
    }

    @Override
    public int changeNum(Integer cid, Integer num) {
        CartEntity cartEntity = cartDao.selectByPrimaryId(cid);
        cartEntity.setNum(cartEntity.getNum() + num);
        return cartDao.updateSelective(cartEntity);
    }

    @Override
    public int delete(Integer cid) {
        return cartDao.delete(cid);
    }

    @Override
    public List<CartVoEntity> findByCids(String cids) {
        String[] cidArray = cids.split(",");
        List<CartVoEntity> cartVoEntityList = new ArrayList<>();
        CartEntity cartEntity = new CartEntity();
        for (String cidStr : cidArray) {
            Integer cid = Integer.parseInt(cidStr);
            cartEntity.setCid(cid);
            List<CartVoEntity> tempList = cartDao.selectCartVoSelective(cartEntity);
            cartVoEntityList.addAll(tempList);
        }
        return cartVoEntityList;
    }
}
